package cn.topcodes.tcsf.admin.service.impl;

import cn.topcodes.tcsf.admin.commons.generic.GenericService;
import cn.topcodes.tcsf.admin.domain.entity.SysMenu;
import cn.topcodes.tcsf.admin.domain.form.NestableSort;
import cn.topcodes.tcsf.admin.mapper.SysMenuMapper;
import cn.topcodes.tcsf.admin.service.res.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly=true)
public class SysMenuServiceImpl extends GenericService<SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    public List<SysMenu> findPermedMenu(Long userId, boolean isDveloper) {
        if(isDveloper) {
            return this.findAllEnable();
        }
        return this.sysMenuMapper.findPermedMenu(userId);
    }

    @Override
    @Transactional(readOnly = false)
    public Long create(SysMenu sysMenu) {
        if(sysMenu.getSort() == null) {
            sysMenu.setSort(0);
        }
        return super.create(sysMenu);
    }

    @Override
    @Transactional(readOnly = false)
    public void saveSort(List<NestableSort> sort) {
        tranSaveSort(sort,null);
    }

    @Transactional(readOnly = false)
    private void tranSaveSort(List<NestableSort> sort,Long parentId) {
        if(sort == null) return;
        for(int i = 0 ; i < sort.size() ; i ++ ) {
            NestableSort s = sort.get(i);
            SysMenu menu = this.findOne(s.getId());
            menu.setSort(i);
            menu.setParentId(parentId);
            this.update(menu);
            tranSaveSort(s.getChildren(),s.getId());
        }
    }
}
